<?php
namespace ac\modules\appcenter\controllers;

use Yii;
use ac\controllers\AuthController;
use common\models\App;
use app\models\CompanyAccountRecord;
use app\modules\developer\models\AppInfo;
use app\modules\company\models\Company;
use app\modules\developer\models\AppPrice;
use common\component\exception\ErrMap;
use common\models\OperationLog;
use common\component\tool\HttpClient;
use common\component\tool\Tool;


class AppcenterController extends AuthController
{

    /*已经开通列表 实例列表*/
    public function actionInstanceList()
    {
        $app = new App;
        $appList = $app::find()
                       ->where('comid = :comid and appid != ""', [':comid' => $this->userInfo['comid']])
                       ->orderBy(['add_time' => SORT_DESC])->asArray()->all();

        // P($appList);
        return Tool::showRes([0, '获取成功'], $appList);
    }

    /*购买应用*/
    public function actionBuyApp()
    {
        if(Yii::$app->request->isPost){
            // P($this->userInfo);
            // P($this->post, false);
            if(isset($this->userInfo['comid']) and $this->userInfo['comid'] != '00000000'){
                /*判断账户金额*/
                $company = Company::find()->select('account')
                            ->where('comid = :comid', [':comid' => $this->userInfo['comid']])
                            ->one();
                if(empty($company)){
                    $account = 0;
                }else{
                    $account = $company->account;
                }
                // P($account);
                /*计算前台需要的金额*/
                if(isset($this->post['App']['buyTime']) and isset($this->post['App']['app_info_id'])){
                    $price = $this->computePrice($this->post['App']['buyTime'], $this->post['App']['app_info_id']);
                }else{
                    $price = 0;
                }
                // P($price);
                if($price == 0 or $price > $account){
                    $backInfo = ErrMap::getError(10031);//返回信息
                }else{
                    // P($this->post);
                    /*取出该应用信息, 比如应用URL*/
                    $appInfo = AppInfo::find()
                            ->select(['flag'])
                            ->where('app_info_id = '. $this->post['App']['app_info_id'])
                            ->one();
                    $appFlag = $appInfo->flag;
                    // P($appInfo);

                    $transaction = Yii::$app->db->beginTransaction();//事物处理
                    $pass = true;
                    try{
                        /*扣除账户金额*/
                        Company::updateAllCounters(['account' => -$price], 'com_id = :com_id', [':com_id' => $this->userInfo['com_id']]);

                        /*开通应用*/
                        $app = new App;
                        if($pass){
                            $this->post['App']['comid'] = $this->userInfo['comid'];
                            if(($appInfo = $app->addApp($this->post, $appFlag)) === false){
                                if($app->hasErrors()){
                                    $backInfo = ErrMap::getError(10005);//返回信息
                                    $exception = $app->getErrors();//异常信息
                                }
                                $pass = false;
                            }
                        }
                        // P($appInfo['appid']);

                        /*添加资金记录*/
                        if($pass){
                            $companyAccountRecord = new CompanyAccountRecord();
                            $data = array(
                                'CompanyAccountRecord' => array(
                                    'comid' => $this->userInfo['comid'],
                                    'appid' => $appInfo['appid'],
                                    'flag' => 2,
                                    'year' => $this->post['App']['buyTime'],
                                    'amount' => $price,
                                    'remark' => '开通应用[' . $this->post['App']['app_name'] . ']'
                                )
                            );
                            // P($data);
                            if(!($amount = $companyAccountRecord->addRecord($data))){
                                if($companyAccountRecord->hasErrors()){
                                    $backInfo = ErrMap::getError(10005);//返回信息
                                    $exception = $companyAccountRecord->getErrors();//异常信息
                                }
                                $pass = false;
                            }
                        }

                        if($pass){
                            $backInfo = [0, '认证中心开通应用成功'];//返回信息
                            $transaction->commit();
                        }
                    }catch(\Exception $exception){
                        $transaction->rollback();       
                    };
                }
            }else{
                $backInfo = ErrMap::getError(10032);//返回信息
            }
        };

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog($this->operationLogArgs($backInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }

    /*购买应用 注释原因：不再使用HTT请求方式开通应用*/
    // public function actionBuyApp()
    // {
    //     if(Yii::$app->request->isPost){
    //         // P($this->userInfo);
    //         // P($this->post, false);
    //         if(isset($this->userInfo['comid']) and $this->userInfo['comid'] != '00000000'){
    //             /*判断账户金额*/
    //             $company = Company::find()->select('account')
    //                         ->where('comid = :comid', [':comid' => $this->userInfo['comid']])
    //                         ->one();
    //             if(empty($company)){
    //                 $account = 0;
    //             }else{
    //                 $account = $company->account;
    //             }
    //             // P($account);
    //             /*计算前台需要的金额*/
    //             if(isset($this->post['Opened']['buyTime']) and isset($this->post['Opened']['app_info_id'])){
    //                 $price = $this->computePrice($this->post['Opened']['buyTime'], $this->post['Opened']['app_info_id']);
    //             }else{
    //                 $price = 0;
    //             }
    //             // P($price);
    //             if($price == 0 or $price > $account){
    //                 $backInfo = ErrMap::getError(10031);//返回信息
    //             }else{
    //                 // P($this->post);
    //                 /*取出该应用信息, 比如应用URL*/
    //                 $appInfo = AppInfo::find()
    //                         ->select(['app_name', 'app_intranet_url', 'app_outside_url', 'outside', 'display'])
    //                         ->where('app_info_id = '. $this->post['Opened']['app_info_id'])
    //                         ->asArray()->one();
    //                 if(!empty($appInfo['app_intranet_url'])){
    //                     $openUrl = $appInfo['app_intranet_url'];//应用内网
    //                 }else if(!empty($appInfo['app_outside_url'])){
    //                     $openUrl = $appInfo['app_outside_url'];//应用外网
    //                 }
    //                 // p($openUrl);

    //                 /*查看当前是否存在没有appid的数据，如果有，说明子应用没有及时返回数据，需手动在我的应用列表中开启*/
    //                 $opened = Opened::find()
    //                             ->where('comid = :comid and appid = ""', [':comid' => $this->userInfo['comid']])
    //                             ->one();
    //                 if(!is_null($opened)){
    //                     $backInfo = ErrMap::getError(10018);//返回信息
    //                 }else{

    //                     $transaction = Yii::$app->db->beginTransaction();//事物处理
    //                     $pass = true;
    //                     try{
    //                         /*扣除账户金额*/
    //                         Company::updateAllCounters(['account' => -$price], 'com_id = :com_id', [':com_id' => $this->userInfo['com_id']]);

    //                         /*添加资金记录*/
    //                         $companyAccountRecord = new CompanyAccountRecord();
    //                         $data = array(
    //                             'CompanyAccountRecord' => array(
    //                                 'comid' => $this->userInfo['comid'],
    //                                 'flag' => 2,
    //                                 'year' => $this->post['Opened']['buyTime'],
    //                                 'amount' => $price,
    //                                 'remark' => '开通应用[' . $this->post['Opened']['app_name'] . ']'
    //                             )
    //                         );
    //                         if(!($amount = $companyAccountRecord->addRecord($data))){
    //                             if($companyAccountRecord->hasErrors()){
    //                                 $backInfo = ErrMap::getError(10005);//返回信息
    //                                 $exception = $companyAccountRecord->getErrors();//异常信息
    //                             }
    //                             $pass = false;
    //                         }

    //                         /*开通应用*/
    //                         $opened = new Opened;
    //                         if($pass){
    //                             $this->post['Opened']['comid'] = $this->userInfo['comid'];
    //                             if( ($opened_id = $opened->addApp($this->post)) === false ){
    //                                 if($opened->hasErrors()){
    //                                     $backInfo = ErrMap::getError(10005);//返回信息
    //                                     $exception = $opened->getErrors();//异常信息
    //                                 }
    //                                 $pass = false;
    //                             }
    //                         }

    //                         /*通知接口开通应用*/
    //                         if($pass){                    
    //                             $httpClient = new HttpClient($openUrl);
    //                             $httpClient->url = '/basic/open-app';
    //                             $httpClient->data = [
    //                                 'appInfoId' => $this->post['Opened']['app_info_id'],//
    //                                 'app_name' => $this->post['Opened']['app_name'],
    //                                 'comid' => $this->userInfo['comid'],//哪个公司买的
    //                                 'buyTime' => $this->post['Opened']['buyTime'],//开通年限
    //                             ];
    //                             if($res = $httpClient->post()){
    //                                 // P($res);
    //                                 // <pre>Array
    //                                 // (
    //                                 //     [code] => 0
    //                                 //     [info] => 开通APP实例成功
    //                                 //     [data] => Array
    //                                 //         (
    //                                 //             [appid] => CMS2019PF312vAxl19
    //                                 //         )
    //                                 // )
    //                                 // </pre>
    //                                 /*返回的appid存入开通列表*/
    //                                 $opened->updateAll(['appid' => $res['data']['appinfo']['appid'], 'appsecret' => $res['data']['appinfo']['appsecret']], 'opened_id = :id', [':id' => $opened_id]);

    //                                 /*返回的appid存入到资金记录表中*/
    //                                 $companyAccountRecord->updateAll(['appid' => $res['data']['appinfo']['appid']], 'comid = :comid', [':comid' => $this->userInfo['comid']]);

    //                                 $backInfo = [0, $this->post['Opened']['app_name'] . '开通应用成功'];//返回信息
    //                             }
    //                         }

    //                         if($pass){
    //                             $backInfo = [0, '认证中心开通应用成功'];//返回信息
    //                             $transaction->commit();
    //                         }
    //                     }catch(\Exception $exception){
    //                         $transaction->rollback();       
    //                     };
    //                 }
    //             }
    //         }else{
    //             $backInfo = ErrMap::getError(10032);//返回信息
    //         }
    //     };

    //     if(!isset($backInfo)){
    //         $backInfo = ErrMap::getError(10005);//返回信息
    //     }
    //     if(!isset($exception)){
    //         $exception = '';//异常信息
    //     }
    //     //操作日志
    //     if(gettype( $res = OperationLog::addLog($this->operationLogArgs($backInfo), $exception) ) != 'boolean'){
    //         return $res;
    //     };
    // }

    /*计算购买价格*/
    private function computePrice($buyTime, $appInfoId)
    {
        $price = 0;
        $buyTime = intval($buyTime);
        $appInfoId = intval($appInfoId);
        $appPrice = AppPrice::find()->where('app_info_id = :app_info_id', [':app_info_id' => $appInfoId])
                        ->asArray()->all();
        // P($appPrice);
        if($buyTime > 0 and !empty($appPrice)){
            foreach($appPrice as $k => $v){
                if($v['year'] == $buyTime){
                    if($this->userInfo['level'] == 0){
                        switch ($buyTime) {
                            case '1':
                                $price = $v['price'];
                                break;
                            case '2':
                                $price = $v['price']*0.9;
                                break;
                            case '3':
                                $price = $v['price']*0.8;
                                break;
                            case '5':
                                $price = $v['price']*0.7;
                                break;
                            case '10':
                                $price = $v['price']*0.6;
                                break;
                        }
                    }else if($this->userInfo['level'] == 1){
                        $price = $v['price']*0.1;
                    }else{
                        switch ($buyTime) {
                            case '1':
                                $price = $v['price']*($this->userInfo['level']/10);
                                break;
                            case '2':
                                $price = $v['price']*($this->userInfo['level']/10)*0.9;
                                break;
                            case '3':
                                $price = $v['price']*($this->userInfo['level']/10)*0.8;
                                break;
                            case '5':
                                $price = $v['price']*($this->userInfo['level']/10)*0.7;
                                break;
                            case '10':
                                $price = $v['price']*($this->userInfo['level']/10)*0.6;
                                break;
                        }
                    }
                }
            }
            return $price;
        }
    }



}